﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;

namespace Web.Controls
{
    public partial class Editor : System.Web.UI.UserControl
    {
        private string LoadContent()
        {
            string path = Server.MapPath(ConfigurationManager.AppSettings["FilePath"]);
            path = Path.Combine(path, this.PlaceName);
            if(File.Exists(path))
                return System.IO.File.ReadAllText(path);
            return string.Empty;
        }
        private void SaveContent(string content)
        {
            string path = Server.MapPath(ConfigurationManager.AppSettings["FilePath"]);
            path = Path.Combine(path, this.PlaceName);

            System.IO.File.WriteAllText(path,content);
        }

        public string PlaceName
        {
            set
            {
                this.ViewState["_PlaceName"] = value;
            } 
            get
            {
                var val = this.ViewState["_PlaceName"] as string;
                return val ?? string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(this.PlaceName))
                    throw new InvalidProgramException("PlaceName is Empty");

                if (this.Page.User.Identity.IsAuthenticated)
                    this.Mode = EditorMode.Edit;
                else
                    this.Mode = EditorMode.View;

                if (this.Mode == EditorMode.View)
                {
                    this.ltrHtml.Text = LoadContent();
                }
                else
                {
                    this.txtEdit.Content = LoadContent();
                }
            }
        }

        protected void btnSave_Click(object sender,EventArgs e)
        {
            SaveContent(this.txtEdit.Content);
            this.Page.ClientScript.RegisterStartupScript(this.GetType(),"success","alert('data saved successfully');",true);
        }

        public EditorMode Mode
        {
            set
            {
                this.ViewState["_Mode"] = value;
                if (value == EditorMode.Edit)
                    this.multiView.ActiveViewIndex = 1;
                else
                    this.multiView.ActiveViewIndex = 0;

            }
            get
            {
                var val = this.ViewState["_Mode"];
                if (val == null)
                    return EditorMode.View;
                return (EditorMode)val;
            }
        }
    }
}
